<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Repository\AreasRepository;
use HiCommon\Repository\CheckpointTypeRepository;
use HiCommon\Repository\ConfigPrivateRepository;
use HiCommon\Repository\ShopImgRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\ShopUserRepository;
use Illuminate\Support\Facades\Hash;

class ShopJoinService extends BaseService
{

    /**
     * 验证申请加盟输入数据
     *
     * @param array $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function check_shop_join_apply_data(&$arr_input = []){
        $arr_data['cate'] = intval($arr_input['cate']);//门店类型 （1检测站，2维修店）
        $arr_data['company_name'] = str_trim($arr_input['company_name']);
        $arr_data['name'] = $arr_input['company_name'];
        $arr_data['logo'] = str_trim($arr_input['logo']);
        $arr_data['img'] = str_trim($arr_input['img']);
        $arr_data['province'] = intval($arr_input['province']);
        $arr_data['city'] = intval($arr_input['city']);
        $arr_data['area'] = intval($arr_input['area']);
        $arr_data['address'] = str_trim($arr_input['address']);
        $arr_data['name_boss'] = str_trim($arr_input['name_boss']);
        $arr_data['phone'] = str_trim($arr_input['phone']);
        $arr_data['pass'] = str_trim($arr_input['pass']);
        $s_confirm_pass = str_trim($arr_input['confirm_pass']);
        $s_phone_code = str_trim($arr_input['phone_code']);
        $arr_data['shop_imgs'] = $arr_input['shop_imgs'];//门店照片
        $arr_data['type'] = intval($arr_input['type']);//检测站
        $arr_data['types'] = str_trim($arr_input['types']);//维修店
        $arr_data['apply_at'] = time_to_ymdhis();

        if(!in_array($arr_data['cate'],[1,2])){
            return hello_error('加盟类型错误');
        }
        if($s_confirm_pass != $arr_data['pass']){
            return hello_error('两次密码不一致');
        }
        if (mb_strlen($arr_data['company_name']) > 30){
            return hello_error('公司名称不能超过50字符');
        }
        if (mb_strlen($arr_data['company_name']) <= 0){
            return hello_error('公司名称不能为空');
        }
        if (mb_strlen($arr_data['logo']) <= 0){
            return hello_error('请上传公司logo');
        }
        if (mb_strlen($arr_data['img']) <= 0){
            return hello_error('请上传营业执照');
        }
        if ($arr_data['province'] <= 0){
            return hello_error('请选择省份');
        }
        if ($arr_data['city'] <= 0){
            return hello_error('请选择城市');
        }
        if ($arr_data['area'] <= 0){
            return hello_error('请选择县区');
        }
        if (mb_strlen($arr_data['address']) <= 0){
            return hello_error('详细地址不能为空');
        }
        if (mb_strlen($arr_data['address']) > 100){
            return hello_error('详细地址不能超过100字符');
        }
        if (mb_strlen($arr_data['name_boss']) > 20){
            return hello_error('老板姓名不能超过20字符');
        }
        if (mb_strlen($arr_data['name_boss']) <= 0){
            return hello_error('老板姓名不能为空');
        }
        if (mb_strlen($arr_data['phone']) != 11){
            return hello_error('请输入11位手机号');
        }
        $res = preg_phone($arr_data['phone']);//手机正则验证
        if ($res['state'] != 0){
            return $res;
        }
        $res = preg_password($arr_data['pass']);//密码正则验证
        if ($res['state'] != 0){
            return $res;
        }
        if($arr_data['cate'] == 1 && $arr_data['type'] <= 0){
            return hello_error('请选择检测机构类型');
        }
//        if($arr_data['cate'] == 2 && mb_strlen($arr_data['types']) <= 0){
//            return hello_error('请选择维修店服务');
//        }
        if(!is_array($arr_data['shop_imgs']) ||  count($arr_data['shop_imgs']) == 0){
            return hello_error('请上传门店照片');
        }
        $s_real_code = redis_phone_code( $arr_data['phone'] );
        if (empty($s_real_code)){
            return hello_error('验证码已过期');
        }
        if ($s_real_code != $s_phone_code){
            return hello_error('验证码错误');
        }
        $arr_input = $arr_data;
        return  hello_success('成功');
    }

    /**
     * 申请加盟
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function shop_join($arr_input){
        //添加加盟数据
        $arr_data_shop = $arr_input;
        $arr_shop_imgs = $arr_data_shop['shop_imgs'];
        unset($arr_data_shop['shop_imgs']);


        //根据详细地址解析经纬度，若是解析失败，使用区的经纬度昨晚店铺经纬度
        $n_areas_id = intval($arr_input['area']);
        $n_city_id = intval($arr_input['city']);
        $s_address = str_trim($arr_input['address']);
        $result = AreasRepository::base_find_one($n_areas_id);
        if(!is_null($result)){
            $arr_data_shop['longitude'] = number_format($result->Lng,6);
            $arr_data_shop['latitude'] = number_format( $result->Lat,6);
        }
        if(!empty($s_address)){
            $result = gaode_api_address_to_location($s_address,$n_city_id);

            if($result['state'] == 0){
                $arr_data_shop['longitude'] = number_format($result['data']['longitude'],6);
                $arr_data_shop['latitude'] = number_format( $result['data']['latitude'],6);
            }
        }


        //根据手机号进行区分门店
        // 没有手机号被注册可以直接申请加盟
        // 已有手机号  1上次审核失败可以更新信息，重新审核 2上次审核成功，提示用户已加盟 3上次审核中，提示用户正在申请中
        $arr_where = ['phone'=>$arr_input['phone']];
        $res = ShopRepository::select_one_by_where($arr_where,['id','phone','status']);
        if(is_null($res)){
            //判断手机号有没有被注册
            $arr_where = ['phone'=>$arr_input['phone']];
            $result = ShopUserRepository::base_get_one($arr_where);
            if(!is_null($result)){
                return hello_error('手机号已被注册');
            }

            //添加加盟商户
            $res = ShopRepository::add_one($arr_data_shop)->toarray();
            if(empty($res)){
                return hello_error('门店主体信息添加失败');
            }
            $n_shop_id = $res['id'];

            //添加商户主账号信息
            $arr_data = [
              'shop_id' => $n_shop_id,
              'is_master' => 1,
              'username' => $arr_input['phone'],
              'phone' => $arr_input['phone'],
              'rong_cloud_id' => 'shop_' . uniqid(),
              'pass' => $arr_input['pass'],
              'password' => Hash::make($arr_input['pass']),
            ];
            $result = ShopUserRepository::base_add_one($arr_data)->toarray();
            if (empty($result)) {
                return  hello_error('申请失败');
            }
        }
        else {
            $arr_shop = $res->toarray();
            $n_shop_id = $arr_shop['id'];
            switch ($arr_shop['status'])
            {
                case 0:
                    return hello_error('申请中，请等待审核结果');
                    break;
                case 1:
                    return hello_error('已通过审核，请前往登录');
                    break;
                case 2:
                    return hello_error('已禁用，请联系客服');
                    break;
                case 3:
                    //修改加盟信息
                    $arr_data_shop['id'] = $n_shop_id;
                    $arr_data_shop['status'] = 0;

                    $res = ShopRepository::edit_one($arr_data_shop);
                    if($res === false){
                        return hello_error('门店主体信息添加失败1');
                    }

                    //删除以前的门店图片
                    $arr_where = ['shop_id'=>$n_shop_id];
                    $res = ShopImgRepository::delete_by_where($arr_where,true);
                    if($res === false){
                        return hello_error('门店主体信息添加失败2');
                    }
                    break;
                default:
                    return hello_error('未知错误');
            }
        }


        $arr_data = arr_one_to_two($arr_shop_imgs,'img',['shop_id'=>$n_shop_id]);
        $res = ShopImgRepository::add_many($arr_data);
        if($res === false){
            return hello_error('门店图片信息添加失败');
        }
        return  hello_success('申请成功');
    }

    /*门店加盟申请*/
    public function api_shop_join_apply($arr_input = []){

        //验证输入数据
        $res = self::check_shop_join_apply_data($arr_input);
        if ($res['state'] != 0){
            return $res;
        }

        //申请加盟
        $res = self::shop_join($arr_input);
        return $res;
    }


    /**
     * 检测站类型列表
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_checkpoint_type_list(){
        $res = CheckpointTypeRepository::get_all()->toarray();
        return  hello_success('查询成功',$res);
    }

    /**
     * 门店加盟申请查询
     *
     * @param $s_phone
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_shop_apply_search($s_phone){
        $s_phone = str_trim($s_phone);
        if(mb_strlen($s_phone) != 11){
            return hello_error('请输入11位手机号');
        }
        $arr_where = ['phone'=>$s_phone];
        $arr_field = ['name','company_name','logo','status','extend','not_pass_reason','apply_at'];
        $res = ShopRepository::get_where_one($arr_where,$arr_field);
        if(is_null($res)){
            return hello_error('没有申请信息');
        }
        $res = $res->toarray();

        return  hello_success('查询成功',$res);

    }

    /*门店类型副标题*/
    public function api_shop_join_subheading(){
        $result = ConfigPrivateRepository::private_config();
        $arr_data = [
          'weixiu_subheading'=>str_trim($result->shop_joinin_wx_content),
          'jiance_subheading'=>str_trim($result->shop_joinin_jc_content),
        ];

        return  hello_success('成功',$arr_data);
    }

}